"""
@name         服务工单回单
@version      1.0
@time         2025/04/07 16:30:49
@description  Retrieve data from the completion and scheduling (service) page of the installation and maintenance scheduling system, 
              select fiber breakage work orders with metering records and light attenuation values between -8 and -26, 
              output business numbers, and require manual receipt.
@author       liuYanXiang,652455342@qq.com
@match        https://133.96.90.208/
@Must-do      Reacquire the JSESSIONID and write it to the file 9_Cookie.
              If you have a better alternative to JSESSIONID, such as session, change it!
"""

import requests
from datetime import datetime, timedelta
import re
import time
import json

message =  f'已完成\n'

def get_jsessionid():
    try:
        with open('9_Cookie', 'r') as file:
            for line in file:
                if line:
                    return line
    except FileNotFoundError:
        print("9_Cookie file not found.")
    return None

def sendmessagetodingtalk(webhook_url, message, mobiles=[]):
    headers = {
        'Content-Type': 'application/json',
        'Charset': 'UTF-8'
    }

    payload = {
        'msgtype': 'text',
        'text': {
            'content': message
        },
        'at': {
            "atMobiles": mobiles,
            "isAtAll": False
        }
    }

    try:
        response = requests.post(webhook_url, headers=headers, data=json.dumps(payload))
        response.raise_for_status()
        result = response.json()
        if result.get('errcode') == 0:
            print('Message sent successfully.')
        else:
            print(f"Message sending failed, error message: {result.get('errmsg')}")
    except requests.RequestException as e:
        print(f'requests error: {e}')

def fetch_data():
    url = "http://10.245.0.60:6038/wms/repairInten/queryRepairCompletionMenuList.do"
    jsessionid = get_jsessionid()
    headers = {
        "Accept": "*/*",
        "Accept-Encoding": "gzip, deflate",
        "Accept-Language": "zh-CN,zh;q=0.9",
        "Connection": "keep-alive",
        "Content-Length": "145",
        "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
        "Cookie": jsessionid,
        "Host": "10.245.0.60:6038",
        "Origin": "http://10.245.0.60:6038",
        "Referer": "http://10.245.0.60:6038/wms/repairInten/replyRepairIntention.do",
        "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.0.0 Safari/537.36",
        "X-Requested-With": "XMLHttpRequest"
    }
    payload = {
        "orgId": "131000",
        "busiNo": "",
        "dealUserId": "",
        "dealMan": "",
        "startDate": "",
        "endDate": "",
        "sourceSys": "0",
        "backStartDate": "",
        "backEndDate": "",
        "orderFlag": "0",
        "subOrderType": "0",
        "rows": "1000",
        "page": "1"
    }

    max_retries = 3
    retries = 0
    while retries < max_retries:
        try:
            response = requests.post(url, headers=headers, data=payload)  
            response.raise_for_status()
            return response
        except requests.RequestException as e:
            print(f"请求发生错误: {e}，重试 {retries + 1}/{max_retries}...")
            retries += 1
            time.sleep(0.8) 

    print("达到最大重试次数，请求失败。")
    return None

def finsh_order(orderid):
    url = 'http://10.245.0.60:6038/wms/repairInten/repairIntentionOrderReply.do'
    jsessionid = get_jsessionid()
    headers = {
        "Accept": "application/json, text/javascript, */*; q=0.01",
        "Accept-Encoding": "gzip, deflate",
        "Accept-Language": "zh-CN,zh;q=0.9",
        "Connection": "keep-alive",
        "Content-Length": "64",
        "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
        "Cookie": jsessionid,
        "Host": "10.245.0.60:6038",
        "Origin": "http://10.245.0.60:6038",
        "Referer": "http://10.245.0.60:6038/wms/repairInten/orderReplyRepairPage.do?sourceSys=9&_=1745199893408",
        "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.0.0 Safari/537.36",
        "X-Requested-With": "XMLHttpRequest"
    }

    payloads = {
        "woIds": orderid,
        "comments": "0", 
        "sourceSys": "9",    
        "repairFlag": "1",
        "repairReason": "110"
    }

    response = requests.post(url=url,headers=headers,data=payloads)
    time.sleep(0.3)
    print(response.text)


def fix_data():
    result = fetch_data()
    data = result.json()
    for item in data["list"]:
        wo_id = item['wo_id']
        busi_no = item["busi_no"]
        get_info(wo_id=wo_id,busi_no=busi_no)

def get_info(wo_id,busi_no):
    global message
    url = f"http://10.245.0.60:6038/wms/repairInten/orderDetail.do?woId={wo_id}&hisFlag=0"
    jsessionid = get_jsessionid()
    headers = {
        "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
        "Accept-Encoding": "gzip, deflate",
        "Accept-Language": "zh-CN,zh;q=0.9",
        "Connection": "keep-alive",
        "Cache-Control": "max-age=0",
        "Cookie": jsessionid,
        "Host": "10.245.0.60:6038",
        "Origin": "http://10.245.0.60:6038",
        "Referer": "http://10.245.0.60:6038/wms/repairInten/replyRepairIntention.do",
        "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.0.0 Safari/537.36",
    }
    response = requests.get(url, headers=headers)
    time.sleep(0.5)
    if(response.status_code == 200):
        if check_html_content(data=response.text) == True:
            message += f'{wo_id}-{busi_no}\n'
            print(wo_id,busi_no)
            # chose = str(input("输入yes/no: "))
            # if chose == 'yes' or chose == 'y':
            finsh_order(wo_id)
            time.sleep(0.3)
def check_html_content(data):
    light_loss_pattern = r'测光衰：光衰值:(-?\d+\.\d+)'
    light_loss_matches = re.finditer(light_loss_pattern, data)
    for match in light_loss_matches:
        light_loss_value = float(match.group(1))
        if 0 > light_loss_value > -26:
            start_index = match.end()
            remaining_content = data[start_index:]
            if "光猫测速结果：设备不在线" not in remaining_content and "不合格" not in remaining_content and "不匹配" not in remaining_content and "不达标" not in remaining_content:
                print(remaining_content)
                return True
    return False

if __name__ == '__main__':
    fix_data()
    sendmessagetodingtalk('https://oapi.dingtalk.com/robot/send?access_token=b48d67f748e84d15ccca047e932c6eb8de30f8f10c054909896d368af1e41368', message, ["16633697998","16633697909"])